package behaviorlearning;

import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;

import org.jdom.Document;
import org.jdom.input.SAXBuilder;

import planninglanguage.goals.Goal;
import planninglanguage.plans.MultiPlan;
import planninglanguage.plans.ParallelPlan;
import planninglanguage.plans.Plan;
import planninglanguage.plans.SequentialPlan;
import planninglanguage.plans.SubGoalPlan;
import util.XMLWriter;


public class CaseSolution {
	static public final int BASICOPERATOR = 0, SEQUENTIAL = 1, PARALLEL = 2, SUBGOAL = 3; 
	int m_type;
	WargusAction m_action;
	LinkedList<CaseSolution> m_subsolutions;
	String m_goal;
	List<Case> m_cases;	// List of cases that are contributing to this behavior
	
	
	public CaseSolution()
	{
		m_type = -1;
		m_action = null;
		m_subsolutions = new LinkedList<CaseSolution>();
		m_goal = null;
		m_cases = new LinkedList<Case>();
	}
	
	public CaseSolution(CaseSolution cs) 
	{
		m_type = cs.m_type;
		if (cs.m_action == null) m_action = null; 
							else m_action = cs.m_action;
		m_subsolutions = new LinkedList<CaseSolution>();
		for(CaseSolution s : cs.m_subsolutions) m_subsolutions.add(new CaseSolution(s));
		m_goal = cs.m_goal;		
		m_cases = new LinkedList<Case>();
		for(Case c:cs.m_cases) m_cases.add(c);								
	}
	
	
	protected Plan toPlan() {
		Plan p = null;
		MultiPlan mp = null;
		
		switch (m_type) {
		case BASICOPERATOR:
			p = m_action.getPlan();
			break;
		case SEQUENTIAL:
			mp = new SequentialPlan(null, null, null);
			for(CaseSolution s : m_subsolutions) {
				mp.add(s.toPlan());
			}
			p = mp;
			break;
		case PARALLEL:
			mp = new ParallelPlan(null, null, null);
			for(CaseSolution s : m_subsolutions) {
				mp.add(s.toPlan());
			}
			p = mp;
			break;
		case SUBGOAL:
			try {
				SAXBuilder sb = new SAXBuilder(false); 
				Document jdoc = sb.build(new StringReader(m_goal));
				Goal g = Goal.loadGoalFromXML(jdoc.getRootElement());
				
				p = new SubGoalPlan(g, null, null, null);
			} catch (Exception e) {
				throw new Error("Unable to parse subgoal in CaseSolution!\n  subgoal = " + m_goal);
			}
			break;
		default: 
			throw new Error("Unsupported plan type in CaseSolution toPlan() " + m_type);
		}		
		return p;
	}
	
	public void writeXML(XMLWriter w) {
		toPlan().writeXML(w);
	}
}
